package com.wys.config;

import com.wys.contants.ReqConstant;
import com.wys.vo.Rtn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.MessageSourceResourceBundle;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * @author NICK_WYS
 * @date 2021/1/20
 */
@ControllerAdvice
@Slf4j
public class I18nResHandler<T> implements ResponseBodyAdvice<T> {

    @Autowired
    private MessageSource messageSource;
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Object attribute = request.getAttribute(ReqConstant.RES_NEED_I18N);
        return attribute != null && (Boolean) attribute;
    }

    @Override
    public T beforeBodyWrite(T t, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(t instanceof Rtn){
            Rtn rtn = (Rtn) t;
            Locale locale = LocaleContextHolder.getLocale();
            String string = messageSource.getMessage(rtn.getMgs(), null, locale);
            if(!StringUtils.isEmpty(string)){
                rtn.setMgs(string);
            }
            return (T) rtn;
        }
        return t;
    }
}
